import { defineStore } from 'pinia';
import type { LoginParams } from '/@/api/model/userModel';
import { login as loginApi, getUserInfo, logout } from '/@/api/user';
// import { PageEnum } from '/@/enums/pageEnum';
import { router } from '/@/router';
import type { UserInfo } from '/#/store';
import { store } from '/@/store';
import { setToken, getToken } from '/@/utils/auth';

interface UserState {
  userInfo: UserInfo | null;
  token?: string;
  lastUpdateTime: number;
  showLogin: boolean;
}

export const useUserStore = defineStore({
  id: 'app-user',
  state: (): UserState => ({
    userInfo: null,
    token: undefined,
    lastUpdateTime: 0,
    showLogin: false,
  }),
  getters: {
    getUserInfo(): UserInfo | null {
      return this.userInfo || null;
    },
    getToken(): string {
      return this.token || getToken() || '';
    },
    getLastUpdateTime(): number {
      return this.lastUpdateTime;
    },
  },
  actions: {
    setToken(info: string | undefined) {
      this.token = info ? info : ''; // for null or undefined value
      setToken(this.token);
    },
    async register() {},
    async login(params: LoginParams) {
      try {
        const data = await loginApi(params);
        const { token } = data;

        // save token
        this.setToken(token);

        return this.afterLoginAction();
      } catch (error) {
        throw error;
      }
    },
    async afterLoginAction() {
      if (!this.getToken) return null;

      // get user info
      const userInfo = await this.getUserInfoAction();

      // redirect
      if (router.currentRoute.value.query.redirect) {
        router.replace(router.currentRoute.value.query.redirect as string);
      }

      return userInfo;
    },
    async getUserInfoAction(): Promise<UserInfo | null> {
      if (!this.getToken) return null;
      try {
        const userInfo = await getUserInfo();
        this.setUserInfo(userInfo);
        return userInfo;
      } catch (err) {
        // 临时处理，info 请求过期报错
        this.logout(false);
        return null;
      }
    },
    setUserInfo(info: UserInfo | null) {
      this.userInfo = info;
      this.lastUpdateTime = new Date().getTime();
    },
    async logout(goLogin = false) {
      if (this.getToken) {
        try {
          await logout();
        } catch {
          console.log('注销Token失败');
        }
      }
      this.setToken(undefined);
      this.setUserInfo(null);
      if (goLogin) {
        this.goLogin();
      }
    },
    goLogin() {
      // if (!this.getToken) {
      this.showLogin = true;
      // }
    },
  },
});

// Need to be used outside the setup
export function useUserStoreWithOut() {
  return useUserStore(store);
}
